package com.cdelink.xzgy.ftp.user.service.impl;

import com.cdelink.xzgy.ftp.common.page.PageRequest;
import com.cdelink.xzgy.ftp.common.page.PageResponse;
import com.cdelink.xzgy.ftp.exception.BaseException;
import com.cdelink.xzgy.ftp.exception.InvalidDataException;
import com.cdelink.xzgy.ftp.user.entity.Records;
import com.cdelink.xzgy.ftp.user.entity.User;
import com.cdelink.xzgy.ftp.user.entity.dto.LoginDto;
import com.cdelink.xzgy.ftp.user.entity.dto.UserDto;
import com.cdelink.xzgy.ftp.user.mapper.one.ConfigMapper;
import com.cdelink.xzgy.ftp.user.mapper.one.RecordsMapper;
import com.cdelink.xzgy.ftp.user.mapper.one.UserMapper;
import com.cdelink.xzgy.ftp.user.mapper.two.UserInfoMapper;
import com.cdelink.xzgy.ftp.user.service.UserService;
import com.cdelink.xzgy.ftp.util.CommonUtil;
import com.cdelink.xzgy.ftp.util.JwtUtil;
import com.cdelink.xzgy.ftp.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author sxl
 * @since 2021-12-13 17:14:25
 */
@Service
public class UserServiceImpl implements UserService {
    static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    //@Resource
    @Autowired(required = false)
    private UserMapper userMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Autowired
    private ConfigMapper configMapper;
    @Autowired
    private RecordsMapper recordsMapper;

    @Autowired
    RedisUtil redisUtil;

    //使用主从-->即xzgy_ftp
    public static int EXECUTE_XZGY_FTP = 1;

    //读取二期数据库
    public static int EXECUTE_XZGY_MIS = 0;
    public int config;


    @Override
    public Map<String, Object> login(LoginDto loginDto) {
        CommonUtil.checkObject(loginDto);
        if (StringUtils.isBlank(loginDto.getAccount()) || StringUtils.isBlank(loginDto.getPassword())) {
            throw new InvalidDataException("账号或密码不能为空");
        }
        getConfig();
        User user = null;
        if (config == EXECUTE_XZGY_MIS) {
            user = userInfoMapper.getUser(loginDto.getAccount(), loginDto.getPassword());
        } else if (config == EXECUTE_XZGY_FTP) {
            user = userMapper.getUser(loginDto.getAccount(), loginDto.getPassword());
        } else {
            throw new BaseException("未在数据库中正确配置数据源");
        }
        if (user == null) {
            throw new InvalidDataException("无效的用户名或密码");
        }
        if (user.getActive() == 0) {
            throw new BaseException("账户未激活");
        }
        return generateToken(user);
    }

    @Override
    public void logout(Integer userId) {
        LOGGER.info("接收到用户{}退出请求", userId);
        if (userId == null) {
            throw new BaseException("退出失败，无法识别用户");
        }
        String format = String.format(RedisUtil.KEY_USER_ID, userId);
        if (redisUtil.hasKey(format)) {
            redisUtil.del(format);
        }
    }

    /**
     * 生成用户token
     *
     * @param user
     * @return
     */
    private Map<String, Object> generateToken(User user) {
        Map<String, Object> map = new HashMap<>();
        String token = JwtUtil.generateUserToken(user, redisUtil);
        map.put("token", token);
        map.put("userInfo", user);
        return map;
    }

    @Override
    public PageResponse<User> getPage(PageRequest<UserDto> pageRequest) {
        CommonUtil.checkObject(pageRequest);
        UserDto userDto = pageRequest.getData();
        CommonUtil.checkObject(userDto);
        if (StringUtils.isNotBlank(userDto.getAccount())) {
            String account = "%" + userDto.getAccount() + "%";
            userDto.setAccount(account);
        }
        if (StringUtils.isNotBlank(userDto.getName())) {
            String name = "%" + userDto.getName() + "%";
            userDto.setName(name);
        }
        Integer pageIndex = Long.valueOf(pageRequest.getOffset()).intValue();
        Integer pageSize = pageRequest.getPageSize();
        PageResponse<User> page = new PageResponse<>();
        Long count = null;
        List<User> userVos = null;
        if (config == EXECUTE_XZGY_MIS) {
            count = userInfoMapper.count(userDto);
            if (count > 0) {
                userVos = userInfoMapper.getPage(pageIndex, pageSize, userDto);
                page.setTotalElements(count);
                page.setData(userVos);
            }
        } else if (config == EXECUTE_XZGY_FTP) {
            count = userMapper.count(userDto);
            if (count > 0) {
                userVos = userMapper.getPage(pageIndex, pageSize, userDto);
                page.setTotalElements(count);
                page.setData(userVos);
            }
        } else {
            throw new BaseException("未能在数据库正确配置数据源");
        }
        return page;
    }

    @Override
    public PageResponse<Records> getPageRecords(PageRequest<Object> pageRequest) {
        CommonUtil.checkObject(pageRequest);
        Integer pageIndex = Long.valueOf(pageRequest.getOffset()).intValue();
        Integer pageSize = pageRequest.getPageSize();
        PageResponse<Records> page = new PageResponse<>();
        Long count = recordsMapper.getCount();
        List<Records> records = null;
        if (count > 0) {
            records = recordsMapper.getPage(pageIndex, pageSize);
        }
        page.setData(records);
        page.setPageIndex(pageRequest.getPageIndex());
        page.setPageSize(pageRequest.getPageSize());
        page.setTotalElements(count);
        return page;
    }


    public void getConfig() {
        int config = configMapper.queryById("FIRSTSTART_EXCUTE");
        this.config = config;
        String s = config == EXECUTE_XZGY_MIS ? "读取xzgy_mis数据库" : "使用xzgy_ftp(主从备份的)数据库";
        System.out.println("+++++++++++获取到的配置++++++++++++++++" + s);
    }

}
